package com.zp.self.module.level_5_设计模式.创建型模式.Ⅳ_原型模式;

import com.google.common.collect.Lists;
import lombok.Data;
import org.junit.Test;

import java.io.*;
import java.util.List;

@Data
class Person implements Cloneable {
    private String name;
    private List<String> foods;

    /**
     * Description: 浅克隆
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    /**
     * Description: 深克隆
     */
    public Object deepClone() throws IOException, ClassNotFoundException {
        /* 写入当前对象的二进制流 */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        /* 读出二进制流产生的新对象 */
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return ois.readObject();
    }

    @Test
    public void testClone() throws CloneNotSupportedException {
        Person nick = new Person();
        nick.setName("Nick");
        nick.setFoods(Lists.newArrayList("米饭", "大肉", "小肉", "蔬菜", "牛奶"));

        Person nickClone = (Person) nick.clone();
        System.out.println(nickClone == nick);//false
        System.out.println(nickClone.getFoods() == nick.getFoods());//true --故属于浅copy
    }

}